<template>
  <div ref="tableWarp" class="ant-row" style="row-gap: 0px">
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <div>
          <!-- 操作按钮区域 -->
          <slot name="extra_" slot="extra"></slot>
          <a-button type="primary" preIcon="ant-design:export-outlined" @click="handleExport"> 导出</a-button>
        </div>
      </template>
      <template v-for="(key, i) in Object.keys(customRender)" #[key]="text, record, index" :key="i">
        <div class="custom-render" @click="addComment(text, record, index, $event)" v-html="customRender[key](text, record)"></div>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, ref, watch, onMounted, nextTick } from 'vue';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { useTable } from '/@/components/Table';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'GraphreportAutoTreeTable',
    components: {
      BasicTable: createAsyncComponent(() => import('/@/components/Table/src/BasicTable.vue'), {
        loading: true,
      }),
    },
    props: {
      items: {
        type: Array,
        default: () => [],
      },
      cggraphreportData: {
        type: Object,
        default: () => {},
      },
      chartData: {
        type: Array,
        default: () => [],
      },
    },
    setup(props) {
      const tableWarp = ref();
      const columns = ref([]); // 需要渲染的表头
      const tableDataSource = ref([]);
      const customRender = ref({});
      const tableWarpWidth = ref(0); // 判断table是否超宽
      const rowIndexColumns = ref({
        // 序号列头
        title: '#',
        dataIndex: 'rowIndex',
        width: 60,
        align: 'center',
        fixed: 'left',
        customRender: ({ index }) => parseInt(index) + 1,
      });

      const $message = useMessage();

      getColunms();
      getTableAddTotalRow();

      const [registerTable] = useTable({
        rowKey: 'id',
        bordered: true,
        canResize: false,
        columns: columns,
        dataSource: tableDataSource,
        showIndexColumn: false,
        pagination: false,
      });

      watch(
        props.items,
        (newValue, oldValue) => {
          console.log('值发生了变更', newValue, oldValue);
          getColunms();
        },
        { deep: true }
      );

      onMounted(() => {
        nextTick(() => {
          if (tableWarp.value) {
            tableWarpWidth.value = tableWarp.value.offsetWidth;
          }
          getColunms();
        });
      });

      function getColunms() {
        // 根据弹窗的数据获取表格的表头
        columns.value = [rowIndexColumns.value];
        const items = JSON.parse(JSON.stringify(props.items));
        items.sort(function (a, b) {
          return a.orderNum - b.orderNum;
        });
        items.forEach((item, i) => {
          if (item.isShow) {
            const column = {
              title: item.fieldTxt,
              dataIndex: item.fieldName,
              width: 100,
            };
            if (i !== 0) {
              column.align = 'center';
            }
            if (item.jsEnhance) {
              column.scopedSlots = { customRender: column.dataIndex };
              var obj = eval('(' + item.jsEnhance + ')');
              customRender.value[column.dataIndex] = obj.customRender;
            }
            columns.value.push(column);
          }
        });
      }

      function getTableScroll() {
        const width = columns.value.length * 100 - 40;
        // 解决表格列分配宽度小于表格宽度时 多一列bug
        if (width < tableWarpWidth.value) {
          columns.value.forEach(function (item) {
            if (item.dataIndex !== 'rowIndex') {
              delete item.width;
            }
          });
        }
        return width > tableWarpWidth.value ? width : false;
      }

      function getTableAddTotalRow() {
        let tableDataSource_;
        if (props.cggraphreportData.head.dataType === 'json') {
          tableDataSource_ = JSON.parse(JSON.stringify(props.chartData));
        } else if (props.cggraphreportData.head.dataType === 'sql' || props.cggraphreportData.head.dataType === 'api') {
          tableDataSource_ = JSON.parse(JSON.stringify(props.cggraphreportData.data.data));
        }
        tableDataSource.value = tableDataSource_;
      }

      // 导出 excel
      function handleExport() {
        const { handleExportXls } = useMethods();
        const url = '/api-online/diagram/diagramConfiguration/exportExcelById';
        const params = {
          id: props.cggraphreportData.head.id,
          name: props.cggraphreportData.head.name,
          params: '',
        };
        handleExportXls(props.cggraphreportData.head.name, url, params);
      }

      return { tableWarp, registerTable, getTableAddTotalRow, handleExport, customRender };
    },
  });
</script>
<style scoped>
  .ant-table td {
    white-space: nowrap;
  }
</style>
<style>
  .custom-render > * {
    display: inline-block;
    min-width: 20px;
    height: 100%;
    border-radius: 5px;
  }
  .custom-render {
    display: inline-block;
  }
</style>
